package com.offcn.order.controller;

import com.offcn.entity.Cart;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.order.service.CartService;
import com.offcn.utils.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private TokenDecode tokenDecode;

    @RequestMapping("/findCartList")
    public List<Cart> findCartList(){
        String username = tokenDecode.getUsername();
        return cartService.findCartListFromRedis(username);
    }

    @RequestMapping("/addGoodsToCartList")
    public Result addGoodsToCartList( Long itemId, Integer num){
        String username = tokenDecode.getUsername();
        //获取购物车数据
        List<Cart> cartList = this.findCartList();
        if (cartList == null) {
            cartList = new ArrayList<Cart>();
        }
        List<Cart> carts = cartService.addGoodsToCartList(itemId, num, cartList);
        cartService.saveCartListToRedis(username,carts);
        return new Result(true, StatusCode.OK,"添加成功");
    }
}
